package com.lry.rpc.netty.server;

import com.lry.common.CommonConstants;
import com.lry.registy.RegistryFactory;
import com.lry.registy.RegistryService;
import com.lry.registy.URL;
import com.lry.rpc.config.NettyServerConfig;
import com.lry.rpc.config.RpcServiceBean;
import com.lry.rpc.netty.Disposable;
import com.lry.rpc.netty.BeanKey;
import com.lry.util.IpUtils;

import java.util.Map;

public class RpcServer implements Disposable, RemotingServer {

    private RegistryService registryService;

    private NettyServerConfig nettyServerConfig;

    public RpcServer(){
        this(new NettyServerConfig());
    }

    public RpcServer(NettyServerConfig nettyServerConfig){
        this.nettyServerConfig = nettyServerConfig;
    }

    @Override
    public void start(){
        start(null);
    }

    public void start(StartOkCallback callback){
        this.registryService = RegistryFactory.getRegistry(nettyServerConfig.getRegitryType(),nettyServerConfig.getRegistryServiceAddress());
        RpcServerBootstrap rpcServerBootstrap = new RpcServerBootstrap(this,nettyServerConfig);
        rpcServerBootstrap.start(callback);
    }

    @Override
    public void startOk() {
        registryServices();
    }

    public void registryServices(){
        //注册服务到注册中心
        //host,port,serviceName,applicationName
        for (BeanKey serviceBeanKey : ServerCache.getServiceBeanKeys()) {

            Map<String,RpcServiceBean> group2RpcServiceBean = ServerCache.getGroupServices(serviceBeanKey);

            for (String group : group2RpcServiceBean.keySet()) {

                URL url = URL.builder().
                        host(IpUtils.getIp()).
                        port(nettyServerConfig.getPort()).
                        applicationName(nettyServerConfig.getApplicationName()).
                        serviceName(serviceBeanKey.getInterfaceName()).
                        implName(serviceBeanKey.getImplName()).
                        build();
                RpcServiceBean rpcServiceBean = group2RpcServiceBean.get(group);
                url.addParam(CommonConstants.WEIGHT,rpcServiceBean.getWeight());
                url.addParam(CommonConstants.VERSION,serviceBeanKey.getVersion());
                url.addParam(CommonConstants.GROUP,group);

                registryService.register(url);
            }
        }
    }

    @Override
    public void shutdown() {
        destroy();
    }

    @Override
    public void destroy() {

    }

    public void registerService(RpcServiceBean rpcServiceBean){
        ServerCache.registerService(rpcServiceBean);
    }

}
